<template>
    <view class="search">
        <view class="top-bar">
            <u-image width="70rpx" height="58rpx" src="/static/rose.png" shape="square" border-radius="4"></u-image>
            <u-search placeholder="请输入关键字" v-model="searchStr" @search="searchReptile" @change="searchHandle" @custom="searchReptile" @focus="focusHandle(true)" @blur="focusHandle(false)" shape="square" margin="0 15rpx" :action-style="searchBtnStyle"></u-search>
            <view class="tip">
                <view class="item" v-for="(item, index) in tipList" :key="index" @click="selectTip(item)">{{ item.name }}</view>
            </view>
            <view class="history">
                <view class="item" v-for="(item, index) in history" :key="index" @click="selectTip(item)">{{item.name}}</view>
            </view>
        </view>
        <plantDetail :plantInfo="plantInfo"></plantDetail>
        <u-back-top :scroll-top="scrollTop"></u-back-top>
    </view>
</template>

<script>
    import {
        loading,
        successToast,
        clearLoad,
        init
    } from '@/common/global.js'
    import api from '@/common/api.js';
    import plantDetail from '@/components/plant-detail.vue'
    export default {
        components: {
            plantDetail
        },
        data() {
            return {
                searchBtnStyle: {
                    background: '#55aaff',
                    color: '#fff',
                    padding: '10rpx',
                    borderRadius: '6rpx'
                },
                plantInfo: null,
                searchStr: '',
                scrollTop: 0,
                tipList: [],
                tipStatus: false,
                history: [] // 搜索记录，保留十条
            };
        },
        methods: {
            /**
             * 查询提示事件
             * */
            searchHandle(evt) {
                if(this.tipStatus) {
                    this.tipList = []
                    this.tipStatus = false;
                    return;
                }
                this.tipList = []
                if(this.searchStr === '') {
                    this.history = uni.getStorageSync('historyTip')
                    console.log('xxx')
                } else {
                    this.history = [];
                }
                this.tipReq(this.searchStr)
            },
            focusHandle(flag) {
                setTimeout(() => {
                    flag ? this.history = uni.getStorageSync('historyTip') : this.history = [];
                }, 0)
            },
            /**
             * 获取输入提示
             * */
            tipReq(keyword, cb) {
                let params = {
                    keyword: keyword
                }
                api.getTip(params, res => {
                    if(res.data.status === 0) {
                        this.tipList = res.data.data;
                        cb && cb();
                    }
                })
            },
            /**
             * 选择输入提示
             * */
            selectTip(item) {
                loading('查询中')
                this.tipStatus = true;
                this.searchStr = item.name;
                this.getSearchReptileReq(item.name);
            },
            /**
             * 选择历史搜索提示
             * */
            historyHandle(item) {
                let flag = false;
                this.history = uni.getStorageSync('historyTip')
                this.history = this.history ? this.history : []
                for(var k in this.history) {
                    if(this.history[k].name === item.name) {
                        let temp = this.history.splice(k, 1)[0];
                        this.history.unshift(temp)
                        flag = true;
                        break;
                    }
                }
                if(!flag) {
                    if(this.length >= 10) {
                        this.history.pop()
                    }
                    this.history.unshift(item)
                }
                uni.setStorage({
                    key: 'historyTip',
                    data: this.history
                })
                this.history = [];
            },
            /**
             * 查询百科百科
             * */
            searchReptile() {
                loading('查询中...');
                this.getSearchReptileReq(this.searchStr);
            },
            /**
             * 根据关键字爬取百度百科数据
             * */
            getSearchReptileReq(keyword) {
                let history = {
                    name: keyword
                }
                this.tipList = []
                this.historyHandle(history);
                api.getReptile({
                    search: keyword
                }, res => {
                    clearLoad();
                    if (res.data.data === null) {
                        successToast(res.data.msg)
                        return;
                    } else {
                        uni.hideLoading()
                        successToast('查询成功！')
                        let json = res.data
                        json.baseInfo = json.baseInfo === '' ? '' : JSON.parse(json.baseInfo);
                        json.formInfo = json.formInfo === '' ? '' : JSON.parse(json.formInfo);
                        json.growInfo = json.growInfo === '' ? '' : JSON.parse(json.growInfo);
                        json.cultiveInfo = json.cultiveInfo === '' ? '' : JSON.parse(json.cultiveInfo);
                        this.plantInfo = {
                            id: json.id,
                            name: json.name,
                            src: json.src,
                            time: json.time,
                            info: [json.baseInfo, json.formInfo, json.growInfo],
                            cultivateInfo: json.cultiveInfo
                        }
                    }
                    this.tipList = []
                })
            },
            // 错误加载图片
            errorHandle(err) {
                console.log('err', err)
            }
        },
        onLoad(options) {
            if (!options['plant']) {
                return;
            }
            this.searchStr = options.plant
            this.searchReptile()
        },
        onPageScroll(e) {
            this.scrollTop = e.scrollTop;
        },
        mounted() {
            // 初始化全局函数的this
            init({
                _this: this
            });
        }
    }
</script>

<style lang="less" scoped>
    @bgColor: #fff;

    .search {
        padding: 15rpx 15rpx 0rpx 15rpx;

        .top-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: @bgColor;
            height: 90rpx;
            
            .tip,
            .history {
                width: 520rpx;
                position: absolute;
                top: 92rpx;
                left: 104rpx;
                z-index: 999;
                // border: 1px solid #e3e3e3;
                border-bottom: none;
                color: #8c8c8c;
                border-radius: 6rpx;
                background: #fff;
                .item {
                    border-bottom: 1px solid #e3e3e3;
                    padding: 5rpx 15rpx;
                    border-radius: 6rpx;
                    padding-left: 50rpx;
                }
            }
        }

        .content {
            .title {
                font-weight: bold;
                margin: 15rpx 0;
                padding: 12rpx;
                background: @bgColor;
            }

            .desc {
                margin-bottom: 30rpx;

                .topic {
                    font-weight: bold;
                    margin: 15rpx 0;
                }

                .text {
                    text-indent: 2em;
                    text-align: justify;
                    text-justify: distribute;
                }
            }

            .main {
                margin-bottom: 40rpx;
                border-radius: 6rpx;

                .img {
                    border: 6rpx dashed #d5d5d5;
                }

                .desc {
                    background: @bgColor;
                    padding: 26rpx 26rpx 40rpx 26rpx;
                }
            }

            .name {
                font-size: 34rpx;
                font-weight: bold;
                text-align: center;
                padding: 15rpx 0 0 0;
                margin-top: 8rpx;
                background: @bgColor;
            }

        }

    }
</style>
